package com.zwz.shiro;

import java.io.IOException;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.StringUtils;
import org.apache.shiro.web.filter.authz.AuthorizationFilter;
import org.apache.shiro.web.util.WebUtils;

/**
 * 重写回调地址
 * @author zhangwanzhong
 * 2015年12月27日 下午8:11:29
 */
public abstract class MyAuthorizationFilter extends AuthorizationFilter {
	
	@Override
	protected boolean onAccessDenied(ServletRequest request,
			ServletResponse response) throws IOException {
		HttpServletRequest httpRequest=(HttpServletRequest)request;
		HttpServletResponse httpResponse=(HttpServletResponse)response;
		Subject subject = getSubject(request, response);
		String type=httpRequest.getHeader("X-Requested-With");
		if(subject.getPrincipal()==null){
			//ajax
			if("XMLHttpRequest".equals(type)){
				System.out.println("请重新登录");
				httpResponse.getWriter().print("{\"code\":\"3\",\"errorMsg\":\"请重新登录\"}");
				return false;
			}else{
				saveRequestAndRedirectToLogin(request, response);
			}
		}else{
			//ajax
			if("XMLHttpRequest".equals(type)){
				System.out.println("你没有权限访问");
				httpResponse.getWriter().print("{\"code\":\"3\",\"errorMsg\":\"你没有权限访问\"}");
				return false;
			}else{
				String unauthorizedUrl = getUnauthorizedUrl();
	            if (StringUtils.hasText(unauthorizedUrl)) {
	                WebUtils.issueRedirect(request, response, unauthorizedUrl);
	            } else {
	                WebUtils.toHttp(response).sendError(HttpServletResponse.SC_UNAUTHORIZED);
	            }
			}
		}
		return false;
	}
}
